<template>
    <Teleport to="#before-navigation" v-if="targetExists">
        <CourseContacts />
    </Teleport>

    <div>
        <h2>{{ $t('course.member.index.page_tit') }}</h2>
        <el-form :model="searchForm" label-width="auto">
            <el-form-item :label="$t('course.member.index.search_form.label_1')" size="large">
                <el-input v-model="searchForm.keyword" :placeholder="$t('course.member.index.search_form.label_1_placeholder')" />
            </el-form-item>
            <el-form-item :label="$t('course.member.index.search_form.label_2')" size="large">
                <el-select v-model="searchForm.role_id" :placeholder="$t('course.member.index.search_form.label_2_placeholder')">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <div class="btn-list">
                <el-button color="#435764" @click="resetFilter">{{ $t('course.member.index.search_form.btn_text_1') }}</el-button>
                <el-button color="#F06423" @click="getCourseMembers">{{ $t('course.member.index.search_form.btn_text_2') }}</el-button>
            </div>
        </el-form>
        <p class="search-res-num">{{ $t('course.member.index.search_form.res_text_1') }} {{ memberList.length }} {{ $t('course.member.index.search_form.res_text_2') }}</p>
        <QuickFilter @filter-change="handleFilterChange" />
        <div class="btn-list" v-if="!roleStore.isStudent">
            <el-button color="#F06423" icon="Plus" @click="addMember">{{ $t('course.member.index.btn_text_1') }}</el-button>
            <el-button color="#435764" icon="Download" @click="downloadTemplate">{{ $t('course.member.index.btn_text_2') }}</el-button>
            <el-upload :show-file-list="false" accept="text/csv" :http-request="handleUpload">
                <el-button color="#F06423" icon="Upload">{{ $t('course.member.index.btn_text_3') }}</el-button>
            </el-upload>
            <el-button color="#F06423" icon="Delete" v-if="checkedMember.length" @click="deleteMember(undefined)">{{ $t('course.member.index.btn_text_4') }}</el-button>
        </div>
        <el-table stripe :data="memberList" :loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column sortable :label="$t('course.member.index.table_label_1')">
                <template #default="{ row }">
                    <div class="user-box" @click="goPage(`/console/user/${row.id}?courseId=${courseId}`)">
                        <div class="user-picture pic">
                            <img :src="row.avatar_url" class="ele" v-if="row.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">{{ row.last_name }} {{ row.first_name }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="email" :label="$t('course.member.index.table_label_2')" width="200" v-if="!roleStore.isStudent" />
            <el-table-column sortable prop="code" :label="$t('course.member.index.table_label_3')" />
            <el-table-column prop="role" :label="$t('course.member.index.table_label_4')" width="100" />
            <el-table-column prop="role" :label="$t('course.member.index.table_label_6')" width="100">
                <template #default="{ row }">
                    <span>{{$t('course.member.index.table_label_6_txt')}}</span>
                </template>
            </el-table-column>
            <el-table-column :label="$t('course.member.index.table_label_5')" width="120" v-if="!roleStore.isStudent">
                <template #default="{ row }">
                    <el-button size="small" circle icon="Edit" @click="editMember(row)"></el-button>
                    <el-button size="small" circle icon="Delete" @click="deleteMember(row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-box">
            <el-pagination
                background
                v-model:page-size="pagination.limit"
                v-model:current-page="pagination.page"
                layout="sizes, prev, pager, next"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                class="mt-4"
                :hide-on-single-page="true"
                @size-change="getCourseMembers"
                @current-change="getCourseMembers"
            />
        </div>
        <!-- 添加/编辑成员 -->
        <el-dialog
            class="mobile-dialog"
            v-model="addDialog"
            width="500"
            :title="`${tag === 'add' ? $t('course.member.index.add_dialog.tit_1') : $t('course.member.index.add_dialog.tit_2')}${$t('course.member.index.add_dialog.tit_3')}`"
            :close-on-click-modal="!addLoading"
        >
            <el-form label-position="top" :model="addMemberForm" ref="addFormRefs" class="add-member-form" :rules="rules" size="large">
                <el-form-item :label="$t('course.member.index.add_dialog.label_1')" required>
                    <el-select v-model="addMemberForm.role_id" :placeholder="$t('course.member.index.add_dialog.label_1_placeholder')" @change="getUserList(undefined)">
                        <el-option v-for="role in roleList.filter(item => item.type !== 3)" :key="role.id" :label="role.name" :value="role.id" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('course.member.index.add_dialog.label_2')" required class="user-select-form-item" v-if="addMemberForm.role_id">
                    <el-select
                        v-model="addMemberForm.userIds"
                        :placeholder="$t('course.member.index.add_dialog.label_2_placeholder')"
                        filterable
                        remote
                        :remote-method="remoteMethod"
                        :disabled="tag === 'update'"
                        class="user-select"
                    >
                        <el-option v-for="item in userList" :key="item.id" :label="`${item.last_name} ${item.first_name}`" :value="`${item.id}`" class="user-select-opt">
                            <div class="user-box">
                                <div class="user-picture">
                                    <span class="pic" v-if="item.avatar_url">
                                        <img src="" class="ele" />
                                    </span>
                                    <el-icon v-else size="30" color="#fff"><User /></el-icon>
                                </div>
                                <div class="user-info">
                                    <div class="fullname">{{ item.last_name }} {{ item.first_name }}</div>
                                    <div class="email">{{ item.email }}</div>
                                </div>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('course.member.index.add_dialog.label_3')" required v-if="addMemberForm.role_id === 3">
                    <el-input v-model="addMemberForm.code" :placeholder="$t('course.member.index.add_dialog.label_3_placeholder')" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button color="#F06423" @click="addMemberHandle" :loading="addLoading">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="addDialog = false" color="#435764" :loading="addLoading">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <!-- 解绑成员 -->
        <el-dialog v-model="delDialog" width="400" :title="$t('course.member.index.del_dialog.tit')" :close-on-click-modal="!delLoading" class="mobile-dialog">
            <p>
                {{ $t('course.member.index.del_dialog.con_1')
                }}{{ checkedMember.length === 1 ? `${checkedMember[0].last_name} ${checkedMember[0].first_name}` : $t('course.member.index.del_dialog.con_2')
                }}{{ $t('course.member.index.del_dialog.con_3') }}
            </p>
            <template #footer>
                <el-button color="#F06423" @click="deleteHandle" :loading="delLoading">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="delDialog = false" color="#435764" :loading="delLoading">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <!-- 批量绑定成员 -->
        <el-dialog v-model="importMemberDialog" width="1000" :title="$t('course.member.index.import_dialog.tit')" class="mobile-dialog">
            <el-table stripe :data="importMember" style="width: 100%" max-height="78vh">
                <el-table-column prop="row" :label="$t('course.member.index.import_dialog.label_1')" width="70" />
                <el-table-column prop="username" :label="$t('course.member.index.import_dialog.label_2')" width="100" />
                <el-table-column :label="$t('course.member.index.import_dialog.label_3')" width="100">
                    <template #default="{ row }">{{ row.firstname }}{{ row.lastname }}</template>
                </el-table-column>
                <el-table-column prop="email" :label="$t('course.member.index.import_dialog.label_4')" width="200" />
                <el-table-column prop="password" :label="$t('course.member.index.import_dialog.label_5')" width="80" />
                <el-table-column prop="idnumber" :label="$t('course.member.index.import_dialog.label_6')" width="160" />
                <el-table-column prop="course" :label="$t('course.member.index.import_dialog.label_7')" width="140" />
                <el-table-column prop="role" :label="$t('course.member.index.import_dialog.label_8')" width="80" />
                <el-table-column fixed="right" :label="$t('course.member.index.import_dialog.label_9')" width="80">
                    <template #default="{ row }">
                        <el-icon size="16" color="#67C23A" v-if="row.status === 'success'"><CircleCheck /></el-icon>
                        <el-icon size="16" color="#E6A23C" v-if="row.status === 'skipped'"><Warning /></el-icon>
                        <el-icon size="16" color="#F56C6C" v-if="row.status === 'failed'"><CircleClose /></el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="message" :label="$t('course.member.index.import_dialog.label_10')" width="200" />
            </el-table>
            <template #footer>
                <el-button color="#F06423" @click="importMemberDialog = false">{{ $t('golbal.btn_text_5') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, UploadRequestOptions } from 'element-plus'

import CourseContacts from '@/components/CourseContacts.vue'
import QuickFilter from '@/components/QuickFilter.vue'

import { goPage, createDownloadA } from '@/utils/global'

import UserService from '@/api/user'
import type { CourseMember, UserInfo } from '@/types/user'

import { useRoleStore } from '@/stores/role'

import CourseService from '@/api/course'
import type { CourseItem, ImportMemberItem } from '@/types/course'

interface FilterParams {
    lastName: string
    firstName: string
}

const route = useRoute()
const roleStore = useRoleStore()
const courseId = computed(() => Number(route.params.courseId))
const loading = ref(false)
const targetExists = ref(false)
const downloadTemplate = () => {
    const csvUrl = new URL('@/assets/template/importUserBindCourse.csv', import.meta.url).href
    createDownloadA(csvUrl, 'importUserBindCourse.csv')
}

const searchForm = reactive({
    keyword: '',
    role_id: '',
})
const roleList = computed(() => roleStore.roles)
const resetFilter = () => {
    searchForm.keyword = ''
    searchForm.role_id = ''
    filters.value = {
        lastName: 'all',
        firstName: 'all',
    }
    getCourseMembers()
}

// 姓氏和名字 筛选
const filters = ref<FilterParams>({
    lastName: 'all',
    firstName: 'all',
})
const handleFilterChange = (newFilters: FilterParams) => {
    filters.value = newFilters
    getCourseMembers()
}

// 成员列表
const memberList = ref<CourseMember[]>([])
const checkedMember = ref<CourseMember[]>([])
const handleSelectionChange = (val: CourseMember[]) => {
    checkedMember.value = val
    console.log(checkedMember.value.length)
}
const addMember = () => {
    tag.value = 'add'
    addMemberForm.value = {
        userIds: '',
        role_id: null,
        code: '',
    }
    addDialog.value = true
}
const editMember = (member: CourseMember) => {
    tag.value = 'update'
    checkedMember.value = [member]
    addMemberForm.value = {
        userIds: `${member.id}`,
        role_id: member.role_id,
        code: member.code,
    }
    addDialog.value = true
}
const deleteMember = (member?: CourseMember) => {
    if (member) checkedMember.value = [member]
    delDialog.value = true
}

import type { Pagination } from '@/types/global'
// 分页器
const pagination = ref<Pagination>({
    page: 1,
    limit: 10,
    total: 10,
})


function getCourseMembers() {
    loading.value = true
    const searchData = {
        keyword: searchForm.keyword,
        role_id: searchForm.role_id,
        first_initial: filters.value.firstName,
        last_initial: filters.value.lastName,
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    UserService.listToCourse(courseId.value, searchData)
        .then(res => {
            memberList.value = res.dataList || [];
            pagination.value = res.pagination || pagination.value
        })
        .finally(() => {
            loading.value = false
        })
}

// 课程信息
const courseInfo = ref<CourseItem>()
function getCourseInfo() {
    CourseService.getById(courseId.value).then(res => {
        courseInfo.value = res
    })
}

// 添加成员弹窗
const addDialog = ref(false)
const addFormRefs = ref<FormInstance>()
const addLoading = ref(false)
const tag = ref('add')
const rules = {
    userIds: [{ required: true, message: '请选择用户', trigger: 'change' }],
    role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
    code: [{ required: true, message: '请输入学生学号', trigger: 'blur' }],
}
const addMemberForm = ref({
    userIds: '',
    role_id: null as number | null,
    code: '',
})
const remoteMethod = (query: string) => {
    getUserList(query)
}
const addMemberHandle = () => {
    addFormRefs.value?.validate((valid: any) => {
        if (valid) {
            addLoading.value = true
            if (tag.value === 'add') {
                CourseService.addMember(courseId.value, addMemberForm.value)
                    .then(() => {
                        addDialog.value = false
                        getCourseMembers()
                    })
                    .finally(() => {
                        addLoading.value = false
                    })
            } else {
                CourseService.upMember(addMemberForm.value.userIds, addMemberForm.value.role_id, addMemberForm.value.code)
                    .then(() => {
                        addDialog.value = false
                        getCourseMembers()
                    })
                    .finally(() => {
                        addLoading.value = false
                    })
            }
        }
    })
}

// 删除成员
const delDialog = ref(false)
const delLoading = ref(false)
const deleteHandle = () => {
    delLoading.value = true
    CourseService.delMember(
        courseId.value,
        checkedMember.value.map(item => item.id),
    )
        .then(() => {
            delDialog.value = false
            getCourseMembers()
        })
        .finally(() => {
            delLoading.value = false
        })
}

// 用户列表
const userList = ref<UserInfo[]>([])
function getUserList(name?: string) {
    if (!addMemberForm.value.role_id) return
    CourseService.members(addMemberForm.value.role_id, courseId.value, name).then(res => {
        userList.value = res
    })
}

// 批量导入成员
const importMember = ref<ImportMemberItem[]>([])
const importMemberDialog = ref(false)
const handleUpload = (options: UploadRequestOptions) => {
    loading.value = true
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('course_id', courseId.value.toString())
    CourseService.importMember(data)
        .then(res => {
            importMember.value = res.results
            importMemberDialog.value = true
            getCourseMembers()
            getCourseInfo()
        })
        .finally(() => {
            loading.value = false
        })
}

watch(
    () => route.fullPath,
    () => {
        getCourseMembers()
        getCourseInfo()
    },
)

onMounted(() => {
    getCourseMembers()
    getCourseInfo()
    targetExists.value = !!document.querySelector('#before-navigation')
})
</script>

<style lang="less" scoped>
.pagination-box{
    justify-content: center;
    margin-top: 25px;
}
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.el-form {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 15px;
    background-color: #f8f9fa;

    display: flex;
    flex-wrap: wrap;
    gap: 0 30px;

    .el-form-item {
        width: calc(50% - 15px);
    }

    .btn-list {
        margin-top: 0;
    }
}

.search-res-num {
    margin-top: 8px;
    margin-bottom: 15px;
    color: #4c4c4c;
    font-size: 15px;
}

.user-box {
    cursor: pointer;

    .user-info {
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        gap: 4px;
    }
}

.btn-list {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    width: 100%;

    .el-button + .el-button {
        margin-left: 0;
    }
}

:deep(.el-dialog) {
    .add-member-form {
        border: none;
        border-radius: 0;
        padding: 0;
        background-color: transparent;

        .el-form-item {
            width: 100%;
        }
    }
}

.user-select-opt {
    margin: 10px 0;
    height: auto;
    line-height: 1;
}
</style>
